<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
     <el-form-item label="学期" prop="semId">
        <el-select v-model="queryParams.semId" filterable clearable placeholder="请选择学期">
          <el-option
            v-for="item in semsterList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
     <el-form-item label="年级" prop="year">
         <el-select v-model="queryParams.year" clearable placeholder="请选择年级"   @change="getClazzList">
             <el-option
             v-for="item in yearList"
             :key="item.value"
             :label="item.label"
             :value="item.value"
             size="small">
           </el-option>
         </el-select>
       </el-form-item>
       <el-form-item label="专业" prop="specId">
         <el-select v-model="queryParams.specId" clearable placeholder="请选择专业"  @change="getClazzList">
           <el-option
             v-for="item in specialtyList"
             :key="item.id"
             :label="item.title"
             :value="item.id"
             size="small">
           </el-option>
         </el-select>
       </el-form-item>
       <el-form-item label="班级" prop="classId">
         <el-select v-model="queryParams.classId" clearable placeholder="请选择班级" filterable>
           <el-option
             v-for="item in clazzList"
             :key="item.id"
             :label="item.title"
             :value="item.id"
             size="small">
           </el-option>
         </el-select>
       </el-form-item>
       <el-form-item label="教师" prop="teacherId">
            <el-select v-model="form.teacherId" placeholder="请输入课程" clearable filterable>
              <el-option
                v-for="dict in teacherList"
                :key="dict.userId"
                :label="dict.name"
                :value="dict.userId"
              />
            </el-select>
       </el-form-item>
       <el-form-item label="课程" prop="courseId">
        <el-select v-model="queryParams.courseId" placeholder="请输入课程" clearable filterable>
          <el-option
            v-for="dict in courseList"
            :key="dict.id"
            :label="dict.title"
            :value="dict.id"
          />
        </el-select>
       </el-form-item>
      <el-form-item label="教室" prop="roomId">
        <el-select v-model="queryParams.roomId" placeholder="请选择教室" filterable clearable size="small">
          <el-option
            v-for="dict in roomList"
            :key="dict.id"
            :label="dict.title"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="周几" prop="week">
       <el-select v-model="queryParams.week" placeholder="请选择周" clearable size="small">
         <el-option
           v-for="dict in weekOptions"
           :key="dict.dictValue"
           :label="dict.dictLabel"
           :value="dict.dictValue"
         />
       </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" icon="el-icon-plus" size="mini" :disabled="doing" @click="handleAuto">自动排课</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="eduSchedulingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学期" align="center" prop="semName" />
      <el-table-column label="专业" align="center" prop="specName" />
      <el-table-column label="课程" align="center" prop="courseName" />
      <el-table-column label="教师" align="center" prop="teacherName" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="教室" align="center" prop="roomName" />
      <el-table-column label="周几" align="center" prop="week" :formatter="weekFormat"/>
      <el-table-column label="节次" align="center" prop="sectionName" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改排课对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学期" prop="semId">
          <el-select v-model="form.semId" filterable clearable placeholder="请选择学期">
            <el-option
              v-for="item in semsterList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="specId">
          <el-select v-model="form.specId" clearable filterable placeholder="请选择专业">
            <el-option
              v-for="item in specialtyList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="color:red">提示：如果有分组教学或者占用特定教室的教学任务,请先手工排课,自动排课时优先级较低！</div>
      <div style="color:red">提示：不选择专业则按学期全部排课！</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEduScheduling, autoScheduling, delEduScheduling, addEduScheduling, updateEduScheduling, exportEduScheduling } from "@/api/education/eduScheduling";
import { getToken } from "@/utils/auth";
import { selectSpecialty} from "@/api/base/specialty";
import { selectSemster} from "@/api/base/semster";
import { selectRoom } from "@/api/base/room";
import { selectClazz } from "@/api/base/clazz";
import { selectCourse} from "@/api/base/course";
import { selectTeacher} from "@/api/base/teacher";
import { selectSection} from "@/api/base/section";

export default {
  name: "EduScheduling",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学期数据
      semsterList: [],
      //起始年
      yearList:[],
      // 专业表格数据
      specialtyList: [],
      // 班级表格数据
      clazzList: [],
      // 教师表格数据
      teacherList: [],
      // 课程数据
      courseList: [],
      // 房间数据
      roomList: [],
      // 排课表格数据
      eduSchedulingList: [],
      // 周状态字典
      weekOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      doing: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskId: null,
        specId: null,
        courseId: null,
        classId: null,
        teacherId: null,
        roomId: null,
        week: null,
        sectionId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskId: [
          { required: true, message: "学期不能为空", trigger: "blur" }
        ],
        specId: [
          { required: true, message: "专业不能为空", trigger: "blur" }
        ],
        courseId: [
          { required: true, message: "课程不能为空", trigger: "blur" }
        ],
        classId: [
          { required: true, message: "班级不能为空", trigger: "blur" }
        ],
        teacherId: [
          { required: true, message: "教师不能为空", trigger: "blur" }
        ],
        roomId: [
          { required: true, message: "教室不能为空", trigger: "blur" }
        ],
        week: [
          { required: true, message: "周几不能为空", trigger: "blur" }
        ],
        sectionId: [
          { required: true, message: "节次不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("common_week").then(response => {
      this.weekOptions = response.data;
    });
    this.getConfigKey("sys.time.start").then(response => {
      var st = parseInt(response.msg);
      var dt = new Date();
      while(st<=dt.getFullYear()+1){
        this.yearList.push({value: st,label: st});
        st ++;
      }
    });
    selectSpecialty({'status':1}).then(response => {
      this.specialtyList = response.rows;
    });
    selectSemster({'status':1}).then(response => {
      this.semsterList = response.rows;
    });
    selectCourse().then(response => {
        this.courseList = response.rows;
        this.total = response.total;
      });
    selectTeacher({'status':1}).then(response => {
        this.teacherList = response.rows;
        this.total = response.total;
      });
    selectRoom({'status':1, type : '1'}).then(response => {
        this.roomList = response.rows;
        this.total = response.total;
      });
  },
  methods: {
    /** 查询排课列表 */
    getList() {
      this.loading = true;
      listEduScheduling(this.queryParams).then(response => {
        this.eduSchedulingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
     /** 查询班级列表 */
    getClazzList() {
      this.loading = true;
      var p = {status:'1'};
      if(this.form.year) p.year = this.form.year;
      if(this.form.specId) p.specId = this.form.specId;
      selectClazz(p).then(response => {
        this.clazzList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskId: null,
        specId: null,
        courseId: null,
        classId: null,
        teacherId: null,
        roomId: null,
        week: null,
        sectionId: null
      };
      this.resetForm("form");
    },
    // 周字典翻译
    weekFormat(row, column) {
      return this.selectDictLabel(this.weekOptions, row.week);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 自动排课 */
    handleAuto() {
      if (this.queryParams.semId != null) {
        this.doing = true;
        autoScheduling(this.queryParams.semId).then(response => {
          if(response.data == 0){
            setTimeout(this.handleAuto, 10000);
          }else{
            this.getList();
            this.doing = false;
          }
          this.msgSuccess(response.msg);
        });

      }else{
        this.msgError("请先选择学期")
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "自动排课";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
            autoScheduling(this.form).then(response => {
              this.msgSuccess("排课成功");
              this.open = false;
              this.getList();
            });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有排课数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportEduScheduling(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
